﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Timers;
using System.Threading;


namespace CqusInfo.CR.Tool
{
    public static class MailSender
    {
        /// <summary>
        /// 发送
        /// </summary>
        /// <returns></returns>
        public static void Send(Email email)
        {
            SendMailPipe.AppendEmail(email);
        }
        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="page">用户点击邮件后的页面：page="/User/Welcome.aspx?id="</param>
        /// <param name="username">用户名</param>
        /// <param name="receivePath">原来的路径</param>
        /// <returns></returns>
        public static bool SendWelcomeMail(string page,string username, string receivePath)
        {
            string emailPath = WebData.APPLICATIONPATH + ConfigurationManager.AppSettings["Email"];
            string emailFrom = System.Configuration.ConfigurationManager.AppSettings["EMailFrom"];
            string url = WebData.WEBURL + page + CqusInfo.CR.Tool.EncodeByBase64.Encode(username + "," + DateTime.Now.ToString());
            Email email = new Email();

            StringBuilder sb_body = new StringBuilder();
            StreamReader objReader = new StreamReader(emailPath);
            string sLine = "";
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    sb_body.Append(sLine);
            }

            objReader.Close();
            string body = string.Format(@sb_body.ToString().Replace('"', '^'), username, url, "023-12345678", emailFrom, DateTime.Now.ToLongDateString());
            body = body.Replace('^', '"');
            email.Body = body; //邮件主题
            email.From = emailFrom; //邮件来源地址
            email.Recipient = receivePath; //邮件目的地址
            email.Subject = "大学生资讯信息网——帐户激活函"; //邮件主题
            try
            {
                Send(email);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
    public static class SendMailPipe
    {
        public static void AppendEmail(Email mail)
        {
            if (mail != null)
            {
                ThreadQueue.AppendItemToPipe(mail);
            }
        }
    }
    public static class ThreadQueue
    {
        private static object lockobj = new object();
        private static List<Email> maillist = new List<Email>();
        static System.Timers.Timer timer = null;
        private static bool isblock = false;
        public static void MailSenderRun()
        {
            timer = new System.Timers.Timer();
            timer.Interval = 10000;
            timer.Elapsed += new ElapsedEventHandler(
                (o, e) =>
                {
                    isblock = true;
                    BeginSend(ref maillist);
                    isblock = false;
                });
            timer.Enabled = true;
            timer.Start();
        }
        public static void AppendItemToPipe(Email item)
        {
            try
            {
                while (isblock)
                {
                    Thread.Sleep(5);
                }
                if (item != null)
                {
                    maillist.Add(item);
                }
            }
            catch (Exception e)
            {
                MyLogger.Error(e.ToString());
            }
        }
        private static void BeginSend(ref List<Email> list)
        {
            try
            {
                foreach (var single in list)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(
                        o =>
                        {
                            send(single);
                        }
                    );
                }
                list = new List<Email>();
            }
            catch (Exception e)
            {
                MyLogger.Error(e.ToString());
            }
        }
        private static void send(object obj)
        {
            Email mail = (Email)obj;
            System.Net.Mail.MailMessage myEmail = new System.Net.Mail.MailMessage();
            Encoding eEncod = Encoding.GetEncoding("utf-8");
            myEmail.From = new System.Net.Mail.MailAddress(mail.From.Trim(), mail.Subject.Trim(), eEncod);
            myEmail.To.Add(mail.Recipient.Trim());
            myEmail.Subject = mail.Subject.Trim();
            myEmail.IsBodyHtml = true;
            myEmail.Body = mail.Body.Trim();
            myEmail.Priority = System.Net.Mail.MailPriority.Normal;
            myEmail.BodyEncoding = Encoding.GetEncoding("utf-8");


            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            smtp.Host = "smtp." + myEmail.From.Host;
            smtp.Credentials = new System.Net.NetworkCredential(mail.MailServerUserName, mail.MailServerPassWord);
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

            try
            {
                smtp.Send(myEmail);
            }
            catch (Exception e)
            {
                MyLogger.Error(e.Message);
            }
        }
    }
    public class Email
    {
        //主题
        private string _subject;
        //内容
        private string _body;
        //邮件来至
        private string _from;
        //SMTP认证时使用的用户名
        private string _username;
        //SMTP认证时使用的密码
        private string _password;
        //收件人的邮箱地址
        private string _recipient;

        public Email()
        {
            _username = System.Configuration.ConfigurationManager.AppSettings["SMTPUserName"].ToString();
            _password = System.Configuration.ConfigurationManager.AppSettings["SMTPPassWord"].ToString();
        }

        /// <summary>
        /// 邮件主题
        /// </summary>
        public string Subject
        {
            get
            {
                return this._subject;
            }
            set
            {
                this._subject = value;
            }
        }

        /// <summary>
        /// 邮件正文
        /// </summary>
        public string Body
        {
            get
            {
                return this._body;
            }
            set
            {
                this._body = value;
            }
        }


        /// <summary>
        /// 发件人地址
        /// </summary>
        public string From
        {
            get
            {
                return _from;
            }
            set
            {
                this._from = value;
            }
        }

        /// <summary>
        /// SMTP认证时使用的用户名
        /// </summary>
        public string MailServerUserName
        {
            get
            {
                return _username;
            }
        }

        /// <summary>
        /// SMTP认证时使用的密码
        /// </summary>
        public string MailServerPassWord
        {
            get
            {
                return _password;
            }
        }


        public string Recipient
        {
            get
            {
                return this._recipient;
            }
            set
            {
                this._recipient = value;
            }
        }

        /// <summary>
        /// 将字符串编码为Base64字符串
        /// </summary>
        /// <param name="str">要编码的字符串</param>
        private string Base64Encode(string str)
        {
            byte[] barray;
            barray = Encoding.Default.GetBytes(str);
            return Convert.ToBase64String(barray);
        }

    }
}
